package com.scvtc.config.security.filter;

import com.scvtc.domain.ResResult;
import com.scvtc.utils.WebUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.scvtc.domain.enums.AppHttpCodeEnum.*;

/**
 * @Description: 认证失败处理器
 * @Author: yiFei
 * @date: 2022/2/15 22:39
 */
@Configuration
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 靠这个错误校验
        authException.printStackTrace();
        // InsufficientAuthenticationException 未登录
        // BadCredentialsException 密码错误
        ResResult<?> result;
        if(authException instanceof BadCredentialsException){
            result = ResResult.customize(BAD_CREDENTIALS);
        }else if(authException instanceof InsufficientAuthenticationException){
            result = ResResult.customize(NEED_LOGIN);
        }else{
            result = ResResult.customize(FAIL_AUTHENTICATION);
        }
        //响应给前端
        WebUtil.resultJson(response,result);
    }
}
